<?php
/* 展项管理相关操作控制器 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class ExhibitTwoController extends HomeController
{
    //列表
    public function list(Request $request)
    {
        try {
            // 分页参数
            $page = $request->input('page', 1);
            $limit = $request->input('limit', 10);
            $no_page = $request->input('no_page', 0);
            $name = $request->input('name');
            $one_id = $request->input('one_id');


            $condition = [];
            if ($name) {
                $condition[] = ['name', 'like', '%' . $name . '%'];
            }
            if ($one_id) {
                $condition[] = ['one_id', '=', $one_id];
            }

            $field = ['id', 'one_id', 'name', 'english_name', 'sort'];
            // $no_page 为真表示不分页查询
            if ($no_page) {
                // 查询数据表
                $data = DB::table('exhibit_two')->where($condition)->select($field)->orderBy('sort', 'asc')->get()->toArray();
            } else {
                // 查询数据表
                $data = DB::table('exhibit_two')->where($condition)->select($field)->orderBy('sort', 'asc')->offset(($page - 1) * $limit)->limit($limit)->get()->toArray();
            }
            
            // 统计总记录数
            $count = DB::table('exhibit_two')->count();

            //整理数组得到一级展项id
            $one_ids = array_column($data, 'one_id');
            //查询数据并返回以id为键，name为值的数组
            $one_data = DB::table('exhibit_one')->whereIn('id', $one_ids)->pluck('name', 'id')->toArray();

            // 合并一级展项数据
            foreach ($data as $key => $item) {
                $data[$key]->one_name = $one_data[$item->one_id];
            }

            return response()->json([
                'code' => HTTP_OK,
                'message' => HTTP_OK_MESSAGE,
                'data' => $data,
                'count' => $count,
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取展项列表失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取展项列表失败',
                'data' => null
            ]);
        }
    }

    //根据上级id获取列表，不分页，供下拉选择框使用
    public function no_page_list(Request $request)
    {
        try {
            // 父级id，默认0表示查询第一级
            $one_id = $request->input('one_id');

            $condition = [];
            $condition[] = ['one_id', '=', $one_id];

            $field = ['id', 'name'];

            // 查询数据表
            $data = DB::table('exhibit_two')->where($condition)->select($field)->orderBy('sort', 'asc')->get()->toArray();

            return response()->json([
                'code' => HTTP_OK,
                'message' => HTTP_OK_MESSAGE,
                'data' => $data,
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取展项列表失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取展项列表失败',
                'data' => null
            ]);
        }
    }

    //添加
    public function insert(Request $request)
    {
        try {
            if (!$request->input('content') || $request->input('content') == '<p><br></p>') {
                return response()->json(['code' => HTTP_ERROR,'message' => '内容不能为空']);
            }

            //接受参数并组装成数组
            $data = [];

            $data['one_id'] = $request->input('one_id');
            $data['name'] = $request->input('name');
            $data['english_name'] = $request->input('english_name') ? : '';
            $data['brief'] = $request->input('brief') ? : '';
            $data['content'] = $request->input('content');
            $data['sort'] = $request->input('sort');
            $data['add_id'] = $this->user_id;

            //添加到数据表
            $id = DB::table('exhibit_two')->insertGetId($data);

            //处理文件
            $img_url = $request->input('img_url');
            if ($img_url) {
                foreach (explode(',', trim($img_url, ',')) as $key => $value) {
                    $item = [];
                    $item['exhibit_id'] = $id;
                    $item['level'] = 2;
                    $item['type'] = 1;
                    $item['url'] = $value;
                    $item['add_id'] = $this->user_id;
                    //添加数据到数据表
                    DB::table('exhibit_item')->insert($item);
                }
            }
            if ($request->input('audio_url')) {
                $item = [];
                $item['exhibit_id'] = $id;
                $item['level'] = 2;
                $item['type'] = 2;
                $item['url'] = $request->input('audio_url');
                $item['add_id'] = $this->user_id;
                //添加数据到数据表
                DB::table('exhibit_item')->insert($item);
            }
            //判断是否有视频
            if ($request->input('video_url')) {
                $item = [];
                $item['exhibit_id'] = $id;
                $item['level'] = 2;
                $item['type'] = 3;
                $item['url'] = $request->input('video_url');
                $item['add_id'] = $this->user_id;
                //添加数据到数据表
                DB::table('exhibit_item')->insert($item);
            }

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('添加展项失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '添加展项失败',
                'data' => null
            ]);
        }
    }

    //删除
    public function delete(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');

            //查询有没有子分类
            $exists = DB::table('exhibit_three')->where('two_id', $id)->exists();
            if ($exists) {
                return response()->json(['code' => HTTP_ERROR,'message' => '存在下级展项，不能删除！']);
            }


            //删除数据
            DB::table('exhibit_two')->where('id', $id)->delete();

            //根据id查询多媒体文件,删除level为2的
            $item = DB::table('exhibit_item')->select('url')->where('level', 2)->where('exhibit_id', $id)->get()->toArray();
            $item = array_column($item, 'url');
            
            //同步删除多媒体文件
            Storage::delete($item);
            DB::table('exhibit_item')->where('level', 2)->where('exhibit_id', $id)->delete();

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('删除展项失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '删除展项失败',
                'data' => null
            ]);
        }
    }


    //修改
    public function update(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');

            if (!$request->input('content') || $request->input('content') == '<p><br></p>') {
                return response()->json(['code' => HTTP_ERROR,'message' => '内容不能为空']);
            }

            //接受参数并组装成数组
            $data = [];

            $data['one_id'] = $request->input('one_id');
            $data['name'] = $request->input('name');
            $data['english_name'] = $request->input('english_name') ? : '';
            $data['brief'] = $request->input('brief') ? : '';
            $data['content'] = $request->input('content');
            $data['sort'] = $request->input('sort');

            //添加到数据表
            DB::table('exhibit_two')->where('id', $id)->update($data);
            
            //处理文件
            $img_url = $request->input('img_url');
            if ($img_url) {
                foreach (explode(',', trim($img_url, ',')) as $key => $value) {
                    //根据id查询多媒体文件是否存在
                    $exists = DB::table('exhibit_item')->where('url', $value)->where('level', 2)->where('exhibit_id', $id)->exists();
                    //存在不用处理，不存在的添加
                    if (!$exists) {
                        $item = [];
                        $item['exhibit_id'] = $id;
                        $item['level'] = 2;
                        $item['type'] = 1;
                        $item['url'] = $value;
                        $item['add_id'] = $this->user_id;
                        //添加数据到数据表
                        DB::table('exhibit_item')->insert($item);
                    }
                }
            }
            $audio_url = $request->input('audio_url');
            if ($audio_url) {
                //根据id查询多媒体文件是否存在
                $exists = DB::table('exhibit_item')->where('url', $audio_url)->where('level', 2)->where('exhibit_id', $id)->exists();
                if (!$exists) {
                    //添加数据到数据表
                    $item = [];
                    $item['exhibit_id'] = $id;
                    $item['level'] = 2;
                    $item['type'] = 2;
                    $item['url'] = $audio_url;
                    $item['add_id'] = $this->user_id;
                    //添加数据到数据表
                    DB::table('exhibit_item')->insert($item);
                }
            }
            $video_url = $request->input('video_url');
            //判断是否有视频
            if ($video_url) {
                //根据id和文件名查询多媒体文件是否存在
                $exists = DB::table('exhibit_item')->where('url', $video_url)->where('level', 2)->where('exhibit_id', $id)->exists();
                if (!$exists) {
                    //添加数据到数据表
                    $item = [];
                    $item['exhibit_id'] = $id;
                    $item['level'] = 2;
                    $item['type'] = 3;
                    $item['url'] = $video_url;
                    $item['add_id'] = $this->user_id;
                    //添加数据到数据表
                    DB::table('exhibit_item')->insert($item);
                }
            }

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('修改展项失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '修改展项失败',
                'data' => null
            ]);
        }
    }

    //详情
    public function detail(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');
            //根据id查询详情
            $data = DB::table('exhibit_two')->where('id', $id)->first();
            //根据上级展项id查询上级展项名称
            $one_name = DB::table('exhibit_one')->where('id', $data->one_id)->value('name');
            $data->one_name = $one_name;

            //根据id查询多媒体文件
            $item = DB::table('exhibit_item')->select('id', 'type', 'url')->where('level', 2)->where('exhibit_id', $id)->orderBy('id','asc')->get()->toArray();
            foreach ($item as $key => $value) {
                $item[$key]->path = $value->url;
                $item[$key]->url = Storage::url($value->url);
            }
            $data->item = $item;

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE,'data' => $data]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取展项详情失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取展项详情失败',
                'data' => null
            ]);
        }
    }


    //列表
    public function mini_list(Request $request)
    {
        try {
            // 分页参数
            $page = $request->input('page', 1);
            $limit = $request->input('limit', 10);
            $no_page = $request->input('no_page', 0);
            $name = $request->input('name');
            $one_id = $request->input('one_id');


            $condition = [];
            // if ($name) {
            //     $condition[] = ['name', 'like', '%' . $name . '%'];
            // }
            // if ($one_id) {
            //     $condition[] = ['one_id', '=', $one_id];
            // }

            $field = ['id', 'one_id', 'name', 'english_name', 'sort'];
            // $no_page 为真表示不分页查询
            if ($no_page) {
                // 查询数据表
                $data = DB::table('exhibit_two')->where($condition)->select($field)->orderBy('one_id', 'asc')->orderBy('sort', 'asc')->get()->toArray();
            } else {
                // 查询数据表
                $data = DB::table('exhibit_two')->where($condition)->select($field)->orderBy('one_id', 'asc')->orderBy('sort', 'asc')->offset(($page - 1) * $limit)->limit($limit)->get()->toArray();
            }
            
            // 统计总记录数
            $count = DB::table('exhibit_two')->count();

            //整理数组得到一级展项id
            $ids = array_column($data, 'id');
            //查询数据并返回以id为键，name为值的数组
            $item_data = DB::table('exhibit_item')->select('id', 'exhibit_id', 'level','type', 'url')->whereIn('exhibit_id', $ids)->where('level', 2)->get()->toArray();


            // 合并一级展项数据
            foreach ($data as $key => $item) {
                foreach ($item_data as $key2 => $value) {
                    //判断是否是当前展项下的多媒体文件
                    if ($item->id == $value->exhibit_id) {
                        $value->url = Storage::url($value->url);
                        if ($value->type == 1) {
                            $data[$key]->img[] = $value->url;
                        } elseif ($value->type == 2) {
                            $data[$key]->audio[] = $value->url;
                        } elseif ($value->type == 3) {
                            $data[$key]->video[] = $value->url;
                        }
                    }
                }
            }

            return response()->json([
                'code' => HTTP_OK,
                'message' => HTTP_OK_MESSAGE,
                'data' => $data,
                'count' => $count,
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取展项列表失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取展项列表失败',
                'data' => null
            ]);
        }
    }

}
